/**
 * CaptchaServlet.java
 *
 * Copyright (C) 2009,  Tomislav Milkovic
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package ws4is.servlets.captcha;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.util.Base64;

/**
 * 
 * @description Simple captcha servlet for login forms. Will use ImageProducer
 *              to create image and stream it out to the browser. Image text
 *              code will be saved in session context attribute 'captcha' thus
 *              enabling any servlet request to check for for validity attribute
 *              value 'captcha' and posted browser code .
 */
public class CaptchaServlet extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
	private static Properties props = new Properties();

	public CaptchaServlet() {
		super();
	}

	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);

		// Switch off disk based caching.
		ImageIO.setUseCache(false);

		Enumeration<?> initParams = conf.getInitParameterNames();
		while (initParams.hasMoreElements()) {
			String key = (String) initParams.nextElement();
			String value = conf.getInitParameter(key);
			props.put(key, value);
		}

	}

	private BufferedImage doGetPicture(HttpServletRequest request,	HttpServletResponse response) throws ServletException, IOException {
		// Set to expire far in the past.
		response.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control",	"no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");

		// return type
		response.setContentType("image/png");
		
		String param = request.getParameter("t");
		if ((param == null) || (param == ""))
			param = "0";

		ImageProducer ip = new ImageProducer(Long.parseLong(param), this.getServletContext());
		ip.setWidth(200);
		ip.setHeight(70);
		ip.setCode_length(6);

		int i = 0;
		if (CaptchaServlet.props.containsKey("width")) {
			i = Integer.parseInt(CaptchaServlet.props.get("width").toString());
			ip.setWidth(i);
		}

		if (CaptchaServlet.props.containsKey("height")) {
			i = Integer.parseInt(CaptchaServlet.props.get("height").toString());
			ip.setHeight(i);
		}

		if (CaptchaServlet.props.containsKey("length")) {
			i = Integer.parseInt(CaptchaServlet.props.get("length").toString());
			ip.setCode_length(i);
		}

		param = request.getParameter("width");
		if (param != null)
			ip.setWidth(Integer.parseInt(param));

		param = request.getParameter("height");
		if (param != null)
			ip.setHeight(Integer.parseInt(param));

		param = request.getParameter("length");
		if (param != null)
			ip.setCode_length(Integer.parseInt(param));

		request.getSession().setAttribute("captcha", ip.getCode());
		return ip.generateImage();

	}


	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		Object obj = request.getParameter("code");
		if (obj == null) {
			BufferedImage bi = doGetPicture(request, response);
			ServletOutputStream out = response.getOutputStream();
			
			String param = request.getParameter("type");
			if ((param!=null)&&("json".equals(param.toLowerCase()))){
				response.setContentType("text/html");
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				ImageIO.write(bi, "png", bos);
				out.write(Base64.encode(bos.toByteArray()));	
			} else{
				ImageIO.write(bi, "png", out);	
			}
				
			
			try {
				out.flush();
			} finally {
				out.close();
			}

		} else {
			PrintWriter pw = response.getWriter();
			pw.print(request.getSession().getAttribute("captcha"));
			pw.flush();
			pw.close();

		} 

	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(request, response);
	}

}
